package com.zzy.utils;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;

@Component("csh")
public class Csh
{
    @Autowired
    GetUrl getUrl;

    @Autowired
    ServletContext servletContext;

    //链接zk,添加节点存储 ip port
    public void zk()
    {
        ZooKeeper zooKeeper =null;

        try{
            zooKeeper = new ZooKeeper("127.0.0.1:2181",10000,null);
        }catch (Exception e)
        {
            System.out.println("链接zooKeeper失败");
        }
        try {
            String myUrl = getUrl.getMyUrl();//获取当前主机ip+port
            zooKeeper.create("/server/a",myUrl.getBytes(), ZooDefs.Ids.READ_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            servletContext.setAttribute("zk",zooKeeper);
        }catch (Exception e)
        {
            System.out.println("添加节点失败");
        }

    }

}
